package com.itlong.cloud.controller.sdkV2.elevator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudDeviceSDKDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKGetByDeviceUniqueDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKServerElevatorKeyDTO;
import com.itlong.cloud.POJO.PO.DeviceElevatorInfoPO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.property.AppCloudElevatorRunState;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.sdk.CloudElevatorSDKGetByDeviceUniqueVO;
import com.itlong.cloud.POJO.VO.sdk.SDKCloudElevatorRobotRunState;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudElevarotErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.equip.sdk.ICloudEntranceSDKServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.user.property.IPropertyRoleServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <desc>
 * 云电梯SDK服务端机器人对旺龙Controller
 * </desc>
 *
 * @createDate 2018/12/27
 */
@RestController
@RequestMapping("/sdk/cloud/elevator/rtl")
public class SDKCloudElevatorRTLController {


    private static final Logger LOG = LoggerFactory.getLogger(SDKCloudElevatorRTLController.class);

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotServiceClient;

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;

    @Autowired
    ICloudEntranceSDKServiceClient iCloudEntranceSDKServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    RedisService redisService;


    /**
     * <desc>
     * 查询唯一标识
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/12/27
     */
    @UnAuthAccessRequired
    public Object getElevatorKey(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus = 0;
        Integer robotDeviceAuthStatus = 0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        List<Map<String, String>> allList = new ArrayList<>();
        CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
        //情况1 机器人白名单授权为 1是 并且机器人设备授权为 1是
        if ("1".equals(robotWhiteListAuthStatus + "")) {
            if (StringUtils.isEmpty(dto.getRobotId())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
            //验证机器人是否有权限(工程人员使用的机器人默认有权限)
            if (iCloudTalkSDKServerUserServiceClient.checkRobotNew(dto) == 0 && !dto.getRoleId().equals(OperateSystemSetUpEnum.ENGINNER.getType().toString())) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
        }
        //设置机器人白名单授权 机器人设备授权
        cloudElevatorSDKServerElevatorKeyDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        cloudElevatorSDKServerElevatorKeyDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        cloudElevatorSDKServerElevatorKeyDTO.setAppId(dto.getAppId());
        cloudElevatorSDKServerElevatorKeyDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKServerElevatorKeyDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotId(robotWhiteListAuthStatus == 0 ? "" : dto.getRobotId());
        // cloudElevatorSDKServerElevatorKeyDTO.setRobotId(dto.getRobotId());
        cloudElevatorSDKServerElevatorKeyDTO.setDeviceType(dto.getRobotDevelopDeviceType());
        Map<String, Object> authMap = iCloudEntranceSDKServiceClient.getDeveloperAuth(dto.getAppId(), dto.getProjectId());
        //无多梯权限
        if (dto.getRoleId().equals(PropertyPublicRoleEnum.ROBOT_DEVELOPER.getRoleId().toString())
                && MultiElevatorAuthEnum.MULTI_ELEVATOR_AUTH.getType().equals(dto.getRobotDevelopDeviceType().toString())
                && MultiElevatorAuthEnum.NONE_ELEVATOR_AUTH.getType().equals(authMap.get("robotNoninductive").toString())) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_NONE_MULTI_CLOUD_ELEVATOR_AUTH_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }
        //无单梯权限
        if (dto.getRoleId().equals(PropertyPublicRoleEnum.ROBOT_DEVELOPER.getRoleId().toString())
                && MultiElevatorAuthEnum.SINGLE_ELEVATOR_AUTH.getType().equals(dto.getRobotDevelopDeviceType().toString())
                && MultiElevatorAuthEnum.NONE_ELEVATOR_AUTH.getType().equals(authMap.get("robotToCloud").toString())) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_NONE_SINGLE_CLOUD_ELEVATOR_AUTH_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }
        LOG.info("======getElevatorKey查询唯一标识============入参================>{}", cloudElevatorSDKServerElevatorKeyDTO.toString());
        List<String> list = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
        list.forEach(str -> {
            Map<String, String> map = new HashMap<>();
            map.put("deviceUnique", str);
            allList.add(map);
        });
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("data", JSON.toJSONString(allList));
        LOG.info("======getElevatorKey查询唯一标识============出参================>{}", signMap.toString());

        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(signMap, dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), allList);
    }


    /**
     * <desc>
     * 根据设备唯一码查询电梯信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/28
     */
    @UnAuthAccessRequired
    public Object getElevatorInfo(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus = 0;
        Integer robotDeviceAuthStatus = 0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        //情况1 机器人白名单授权为 1是 并且机器人设备授权为 1是
        if ("1".equals(robotWhiteListAuthStatus + "")) {
            if (StringUtils.isEmpty(dto.getRobotId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
            cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(dto.getRobotId());

        }

        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());

        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);

        //传入机器人白名单授权状态和机器人设备授权状态
        dto.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        dto.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        dto.setRobotId(robotWhiteListAuthStatus == 0 ? "" : dto.getRobotId());
        LOG.info("======getElevatorInfo根据设备唯一码查询电梯信息============入参================>{}", dto.toString());

        //设备权限以及机器人权限验证
        int result = this.checkDeveloperAuth(dto);
        if (result == 1) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        } else if (result == 2 && !dto.getRoleId().equals(OperateSystemSetUpEnum.ENGINNER.getType().toString())) {
            return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }
        List<CloudElevatorSDKGetByDeviceUniqueVO> list = iCloudElevatorSDKServerCloudServiceClient.getElevatorInfo(cloudElevatorSDKGetByDeviceUniqueDTO);
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("data", JSON.toJSONString(list));
        LOG.info("======getElevatorInfo根据设备唯一码查询电梯信息============出参================>{}", signMap.toString());

        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(signMap, dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), list);
    }

    /**
     * <desc>
     * 获取电梯时时状态。
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2018-12-29
     */
    @UnAuthAccessRequired
    public Object getElevatorOftenStatus(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus = 0;
        Integer robotDeviceAuthStatus = 0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        //情况1 机器人白名单授权为 1是 并且机器人设备授权为 1是
        if ("1".equals(robotWhiteListAuthStatus + "")) {
            if (StringUtils.isEmpty(dto.getRobotId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
        }
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(robotWhiteListAuthStatus == 0 ? "" : dto.getRobotId());

        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);


        dto.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        dto.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        dto.setRobotId(robotWhiteListAuthStatus == 0 ? "" : dto.getRobotId());
        LOG.info("======getElevatorOftenStatus获取电梯时时状态============入参================>{}", null == cloudElevatorSDKGetByDeviceUniqueDTO ? "" : cloudElevatorSDKGetByDeviceUniqueDTO.toString());

        //设备权限以及机器人权限验证
        int result = this.checkDeveloperAuth(dto);
        if (result == 1) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            //工程人员默认有项目下的机器人权限
        } else if (result == 2 && !dto.getRoleId().equals(OperateSystemSetUpEnum.ENGINNER.getType().toString())) {
            return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }

        List<AppCloudElevatorRunState> eleRunStatesVO = iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique(),
                cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
        List<SDKCloudElevatorRobotRunState> list = new ArrayList<>();
        for (AppCloudElevatorRunState appCloudElevatorRunState : eleRunStatesVO) {
            SDKCloudElevatorRobotRunState sdkCloudElevatorRobotRunState = new SDKCloudElevatorRobotRunState();
            sdkCloudElevatorRobotRunState.setCodeName(appCloudElevatorRunState.getCodeName());
            sdkCloudElevatorRobotRunState.setDeviceUnique(appCloudElevatorRunState.getDeviceUnique());
            sdkCloudElevatorRobotRunState.setFloorNum(appCloudElevatorRunState.getFloorNum());
            sdkCloudElevatorRobotRunState.setLiftState(appCloudElevatorRunState.getLiftState());
            sdkCloudElevatorRobotRunState.setDoorStatus(appCloudElevatorRunState.getDoorStatus());
            sdkCloudElevatorRobotRunState.setIsOnline(appCloudElevatorRunState.getIsOnline());
            sdkCloudElevatorRobotRunState.setElevatorNum(appCloudElevatorRunState.getDeviceUnique().substring(appCloudElevatorRunState.getDeviceUnique().length() - 4, appCloudElevatorRunState.getDeviceUnique().length()).replaceAll("^(0+)", ""));
            sdkCloudElevatorRobotRunState.setTimestamp(appCloudElevatorRunState.getTimestamp());
            list.add(sdkCloudElevatorRobotRunState);
        }
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("data", JSON.toJSONString(list));
        LOG.info("======getElevatorOftenStatus获取电梯时时状态============出参================>{}", signMap.toString());

        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(signMap, dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), list);
    }

    /**
     * <desc>
     * 预约电梯
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @RequestMapping(value = "/callElevator", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_CALL_ELEVATOR)
    @ResponseBody
    public Object callElevator() {
        //收到请求的时间
        long requestTime = (new Date()).getTime();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO cloudElevatorSDKCallElevatorDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            cloudElevatorSDKCallElevatorDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKCallElevatorDTO.setAppSecret(request.getAttribute("appSecret").toString());
            cloudElevatorSDKCallElevatorDTO.setRobotDevelopDeviceType(2);
            cloudElevatorSDKCallElevatorDTO.setDeviceType("1");
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKCallElevatorDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            //初始值为 登录为工程人员登录  获取项目下所有的设备
            Integer robotWhiteListAuthStatus = 0;
            Integer robotDeviceAuthStatus = 0;
            if (!"1".equals(cloudElevatorSDKCallElevatorDTO.getRoleId())) {
                Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(cloudElevatorSDKCallElevatorDTO.getProjectId(), cloudElevatorSDKCallElevatorDTO.getAppId());
                robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
                robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
            }
            cloudElevatorSDKCallElevatorDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            cloudElevatorSDKCallElevatorDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);

            if ("1".equals(robotWhiteListAuthStatus + "")) {
                if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getProjectId()) || StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getRobotId())) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
                }
            }
            LOG.info("======callElevator预约电梯RTL============入参================>{}", cloudElevatorSDKCallElevatorDTO.toString());

            //设备权限以及机器人权限验证
            int result = this.checkDeveloperAuth(cloudElevatorSDKCallElevatorDTO);
            if (result == 1) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            } else if (result == 2) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }

            //云电梯设备判断,标准版不支持机器人功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }

            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(cloudElevatorSDKCallElevatorDTO.getFromFloor(),
                    cloudElevatorSDKCallElevatorDTO.getToFloor(), cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            if (floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            if ("1".equals(robotWhiteListAuthStatus + "")) {
                //判断当前机器人之前预约行程是否完成
                Integer operateStatus = iCloudElevatorSDKRobotServiceClient.checkSuccessState(cloudElevatorSDKCallElevatorDTO.getRobotId(), cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
                if (operateStatus != null && operateStatus != 2) {//有行程,1分钟之内不是完成状态不允许再次呼梯
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_ROBOT_CALL_ELEVATOR_RECORD_ERR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
                }
            }
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(vo.getIotProductKey(), cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            //调用IOT呼梯(把requestId传入)
            //snr之前传的null
            String snr = LogicIdUtil.bussinessId();
            LOG.info("【呼梯日志 requestId requestTime snr】{} {} {}", cloudElevatorSDKCallElevatorDTO.getRequestId(), requestTime, snr);
            iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKCallElevatorDTO.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("goFloor").toString(), floor.get("fromFloor").toString(), null,
                    CloudElevatorCallTypeEnum.OUT.getType(), null, CallElevatorSourceTypeEnum.ROBOT.getType(), cloudElevatorSDKCallElevatorDTO.getRobotId(), snr, cloudElevatorSDKCallElevatorDTO.getCtrElevator(), 1, cloudElevatorSDKCallElevatorDTO.getUpDown(), null, cloudElevatorSDKCallElevatorDTO.getRequestId());
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            saveDTO.setFromFloor(floor.get("fromNaturalFloor").toString());
            saveDTO.setToFloor(floor.get("goNaturalFloor").toString());
            saveDTO.setProjectId(cloudElevatorSDKCallElevatorDTO.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            saveDTO.setUserId(cloudElevatorSDKCallElevatorDTO.getRobotId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp,
                            cloudElevatorSDKCallElevatorDTO.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_callElevator】预约电梯异常", e);
        }
    }

    /**
     * <desc>
     * 公共参数权限判断
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/09/18
     */
    @UnAuthAccessRequired
    public Object publicParamCheck(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus = 0;
        Integer robotDeviceAuthStatus = 0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        //情况1 机器人白名单授权为 1是 并且机器人设备授权为 1是
        if ("1".equals(robotWhiteListAuthStatus + "")) {
            if (StringUtils.isEmpty(dto.getRobotId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), "", "");
            }
        }
        dto.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        dto.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        dto.setRobotId(robotWhiteListAuthStatus == 0 ? "" : dto.getRobotId());
        //设备权限以及机器人权限验证
        int result = this.checkDeveloperAuth(dto);
        if (result == 1) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), "", "");
        } else if (result == 2) {
            return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), dto.getRequestId(), "", "");
        }
        return null;
    }

    /**
     * <desc>
     * 发送开门关门指令
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/12/28
     */
    @ResponseBody
    @PostMapping("/sendOpenAndCloseDoor")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SEND_OPEN_CLOSE_DOOR_LOG_DESC)
    public Object sendOpenAndCloseDoor() {
        //收到请求的时间
        long requestTime = (new Date()).getTime();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO cloudElevatorSDKServerSendCommandDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            cloudElevatorSDKServerSendCommandDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKServerSendCommandDTO.setAppSecret(request.getAttribute("appSecret").toString());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKServerSendCommandDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            //初始值为 登录为工程人员登录  获取项目下所有的设备
            Integer robotWhiteListAuthStatus = 0;
            Integer robotDeviceAuthStatus = 0;
            if (!"1".equals(cloudElevatorSDKServerSendCommandDTO.getRoleId())) {
                Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(cloudElevatorSDKServerSendCommandDTO.getProjectId(), cloudElevatorSDKServerSendCommandDTO.getAppId());
                robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
                robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
            }
            cloudElevatorSDKServerSendCommandDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            cloudElevatorSDKServerSendCommandDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
            String responseTimestamp = new Date().getTime() + "";
            LOG.info("======sendOpenAndCloseDoor发送开门关门指令RTL============入参================>{}", cloudElevatorSDKServerSendCommandDTO.toString());

            if (StringUtils.isBlank(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            if ("1".equals(robotWhiteListAuthStatus + "")) {
                if (StringUtils.isEmpty(cloudElevatorSDKServerSendCommandDTO.getRobotId()) || StringUtils.isEmpty(cloudElevatorSDKServerSendCommandDTO.getDeviceType()) || cloudElevatorSDKServerSendCommandDTO.getEffectiveTime() == null) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
                }
            }
            //设备权限以及机器人权限验证
            int result = this.checkDeveloperAuth(cloudElevatorSDKServerSendCommandDTO);
            if (result == 1) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            } else if (result == 2) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            //云电梯设备判断,标准版不支持机器人功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique());
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            Integer effectiveTime = cloudElevatorSDKServerSendCommandDTO.getEffectiveTime();
            if (effectiveTime < 0 || effectiveTime > 99) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_EFFECTIVE_TIME_OUT_ERR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }
            //放入requestId
            //snr之前传的null
            String snr = LogicIdUtil.bussinessId();
            LOG.info("【开关门日志 requestId requestTime snr】{} {} {}", cloudElevatorSDKServerSendCommandDTO.getRequestId(), requestTime, snr);
            if (cloudElevatorSDKServerSendCommandDTO.getType() == 1) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.OPEN.getType(), effectiveTime, CallElevatorSourceTypeEnum.ROBOT.getType(), null, snr, null, 1, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, cloudElevatorSDKServerSendCommandDTO.getRequestId());
            }
            if (cloudElevatorSDKServerSendCommandDTO.getType() == 2) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.CLOSE.getType(), effectiveTime, CallElevatorSourceTypeEnum.ROBOT.getType(), null, snr, null, 1, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, cloudElevatorSDKServerSendCommandDTO.getRequestId());
            }
            //判断电梯当前状态是否是开门，如果是开门则返回成功，否则返回失败
            boolean isOpen = false;
            int count = 0;
            while (count < 5) {
                Thread.sleep(900);
                //IotCloudElevatorStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE +
                //cloudElevatorSDKServerSendCommandDTO.getDeviceUnique()), IotCloudElevatorStateDTO.class);
                //还必须判断开门指令被成功执行了
                if (isDeviceExecute(snr)) {
                    isOpen = true;
                    break;
                }
                //else {
                //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                //iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), "");
                //}
                count++;
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isOpen", isOpen + "");

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", new JSONObject(resultMap));//签名使用json格式内容进行
            LOG.info("======sendOpenAndCloseDoor发送开门关门指令RTL============出参================>{}", signMap.toString());

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(),
                    responseTimestamp, Md5EncryptUtil.getSDKV2Md5(signMap, cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, cloudElevatorSDKServerSendCommandDTO.getAppSecret()), resultMap);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_sendOpenAndCloseDoor】发送开门关门指令失败", e);
        }
    }

    /**
     * <desc>
     * 开发者权限判断
     * <desc/>
     *
     * @param dto
     * @return
     * @author Qiang.S
     * @createDate 2019-09-18
     */
    @UnAuthAccessRequired
    public int checkDeveloperAuth(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(dto.getRobotWhiteListAuthStatus() == 0 ? "" : dto.getRobotId());

        CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
        cloudElevatorSDKServerElevatorKeyDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
        cloudElevatorSDKServerElevatorKeyDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
        cloudElevatorSDKServerElevatorKeyDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotId(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotWhiteListAuthStatus(dto.getRobotWhiteListAuthStatus());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotDeviceAuthStatus(dto.getRobotDeviceAuthStatus());
        if ("4".equals(dto.getDeviceType())) {//机器人无感
            cloudElevatorSDKServerElevatorKeyDTO.setDeviceType(1);
            dto.setRobotDevelopDeviceType(1);
        } else if ("1".equals(dto.getDeviceType())) {//云电梯机器人对云端
            cloudElevatorSDKServerElevatorKeyDTO.setDeviceType(2);
            dto.setRobotDevelopDeviceType(2);
        }
        List<String> deviceUniques = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
        if (deviceUniques == null || deviceUniques.isEmpty()) {
            return 1;
        } else {
            //判断入参中deviceUnique中是否全部包含查询出的结果
            for (String deviceUniqueAuth : cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique().split(",")) {
                int flag = 0;
                for (String deviceUnique : deviceUniques) {
                    if (deviceUnique.equals(deviceUniqueAuth)) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) {
                    return 1;
                }
            }
        }
        //验证机器人是否有权限
        if (iCloudTalkSDKServerUserServiceClient.checkRobotNew(dto) == 0 && !OperateSystemSetUpEnum.ENGINNER.getType().toString().equals(dto.getRoleId())) {
            return 2;
        }
        return 0;
    }

    /*
        根据snr判断设备是否成功执行了命令
        缓存存在就是执行成功:
            1.阿里执行成功了设备才会报
            2.华为执行成功了才会写入缓存
        直接查2次缓存
        阿里的结构
        {
            "cmd": "1003",
            "data": [
                {
                    "details": "success",
                    "msg": "成功",
                    "msgCode": 0,
                    "snr": 0
                }
            ],
            "details": "success",
            "msg": "成功",
            "msgCode": 0,
            "snr": 0
        }
    */
    private boolean isDeviceExecute(String snr) {
        String ali = redisService.get(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE + "_ali_" + snr);
        String hw = redisService.get(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE + "_hw_" + snr);
        boolean b1 = (ali != null && !ali.equals(""));
        boolean b2 = (hw != null && !hw.equals(""));
        if (b1 || b2) {
            return true;
        }
        return false;
    }

}